# -*- coding: utf-8 -*-

import sys
import os
import importlib


class ModuleLoader(object):
    """docstring for ModuleLoader."""

    ModuleHash = {}
    reload = False

    def __init__(self):
        super(ModuleLoader, self).__init__()

    @classmethod
    def debug(cls, isDebug=True):
        if isDebug:
            cls.reload = True
        else:
            cls.reload = False

    @classmethod
    def loadByHash(cls, hash, root="", default_attr=False):
        try:
            p = hash.replace(".", "/") + ".py"
            file = os.path.join(root, p)

            if os.path.exists(file):
                name = hash
                module = cls.load(name, file)
                if module:
                    if default_attr:
                        if hasattr(module, default_attr):
                            return getattr(module, default_attr)
                    else:
                        return module

            hl = hash.split(".")
            if len(hl) > 1:
                p = "/".join(hl[:-1])+".py"
                file = os.path.join(root, p)
                api_name = hl[-1]
                if os.path.exists(file):
                    name = ".".join(hl[:-1])
                    module = cls.load(name, file)
                    if module:
                        if hasattr(module, api_name):
                            return getattr(module, api_name)

        except Exception as e:
            pass
        return None

    @classmethod
    def load(cls, name, path):

        try:
            if name in cls.ModuleHash:
                if cls.reload:
                    # importlib.reload(cls.ModuleHash[name])
                    # print("reload")
                    pass
                else:
                    return cls.ModuleHash[name]

            if os.path.exists(path):
                module = cls.loadModule(name, path)

                if module:
                    cls.ModuleHash[name] = module
                    return cls.ModuleHash[name]
        except Exception as e:
            raise

        return None

    @classmethod
    def loadModule(cls, name, path):
        module = False
        try:

            module_spec = importlib.util.spec_from_file_location(
                name, path
            )
            modules = importlib.util.module_from_spec(module_spec)
            # print("aaa",modules)
            module_spec.loader.exec_module(modules)
            # print("module_spec",module_spec)
            module = modules
        except Exception as e:
            raise

        return module
